// pages/address/list/index.js
import {reqAddressList,reqDelAddress} from '../../../api/address'
import {swiperCellBehavior} from '../../../../../behaviors/swiperCell'

// 获取应用实例
const app = getApp()
Page({
  behaviors:[swiperCellBehavior],
  // 页面的初始数据
  data: {
    addressList: [],
  },
 delAddress(event){
    const { id } = event.currentTarget.dataset
    wx.showModal({
      title: '删除',
      content: '您确定要删除吗',
      success:async(res)=>{
        if(res.confirm){
          await reqDelAddress(id)
          wx.toast({title:'删除成功'})
          this.getAddressList()
        }
      }
    })
  },

  // 去编辑页面
  toEdit(event) {
    const { id } = event.currentTarget.dataset
    wx.navigateTo({
  url: `/module/settingModule/pages/address/add/index?id=${id}`
    })
  },
  // 获取收货地址列表数据
  async getAddressList (){
    const {data:addressList} = await reqAddressList()
    this.setData({addressList})
  },
  changeAddress(e){
    if(this.flag !=='1') return
    const addressId = e.currentTarget.dataset.id

    const selectAddress = this.data.addressList.find(item=>item.id===addressId)
    if(selectAddress){
      app.globalData.address = selectAddress
      wx.navigateBack()
    }
  },
  onShow(){
    this.getAddressList()
  },
  onLoad(options){
    this.flag=options.flag
  }
})
